package com.zhangjianling.premp.server.sys.impl;

import com.zhangjianling.premp.dao.sys.SysDeptDao;
import com.zhangjianling.premp.entity.sys.SysDept;
import com.zhangjianling.premp.server.sys.SysDeptService;
import com.zhangjianling.premp.utils.SystemAopLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
@Transactional
public class SysDeptServiceImpl implements SysDeptService {

	@Resource
	private SysDeptDao sysDeptDao;

	@Override
	public SysDept saveDept(SysDept dept) {
		return sysDeptDao.save(dept);
	}

	@Override
	public SysDept findDept(String deptId) {
		return sysDeptDao.findById(deptId).get();
	}

	@Override
	@SystemAopLog(description="删除部门")
	public void deleteDept(String deptId) {
		SysDept sysDept = new SysDept();
		sysDept.setDeptId(deptId);
		sysDeptDao.delete(sysDept);
	}

	@Override
	public Page<SysDept> pageList(int pageNumber,int pageSize,String sortColom,final SysDept dept) {
		Pageable pageable = new PageRequest(pageNumber-1, pageSize, Sort.Direction.ASC,sortColom);
		Page<SysDept> sysDept = sysDeptDao.findAll(new Specification<SysDept>(){
			@Override
			public Predicate toPredicate(Root<SysDept> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(StringUtils.isNotBlank(dept.getName())){
					list.add(criteriaBuilder.like(root.get("name").as(String.class), "%" +dept.getName()+"%"));
				}
				if(null!=dept.getCreateTime() && !"".equals(dept.getCreateTime())){
					list.add(criteriaBuilder.like(root.get("createTime").as(String.class),"%"+ dept.getCreateTime()+"%"));
				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		},pageable);
		return sysDept;
	}

	@Override
	public SysDept findDept(SysDept dept) {
		return sysDeptDao.findByName(dept);
	}

	@Override
	public List<SysDept> findTopList() {
		return sysDeptDao.findTopList();
	}

	@Override
	public SysDept findByDeptCode(String deptCode) {
		// TODO Auto-generated method stub
		return sysDeptDao.findByDeptCode(deptCode);
	}
}
